package com.xiaode.controller.app.teacher.pair;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.*;
import com.xiaode.common.model.dto.notice.PairNoticeDTO;
import com.xiaode.exce.EnumError;
import com.xiaode.util.ChatUtil;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PairService {

    /**
     * 结对列表
     */
    public Ret pairStudentPage(Integer teacherId, Integer state, Integer page, Integer limit, String keyWord) throws Exception {
        Page<TeacherStudent> tsPage = TeacherStudent.dao.template("pairStudentPage", Kv.by("teacherId", teacherId).setIfNotNull("state", state).setIfNotNull("keyWord", keyWord)).paginate(page, limit);
        return Ret.ok("tsPage", tsPage);
    }

    /**
     * 确认结对
     * TODo
     */
    public Ret pairConfirm(Admin admin, Integer pairId, Integer state) throws Exception {
        Integer teacherId = admin.getId();
        PairNoticeDTO noticeDTO = new PairNoticeDTO();

        //查询教师与学生关系
        TeacherStudent ts = TeacherStudent.dao.findById(pairId);
        if (BeanUtil.isEmpty(ts)) {
            return Ret.fail().set("error", EnumError.APPLY_NULL.getObj());
        }
        TeacherStudent tsConfirm = TeacherStudent.dao.findFirst("SELECT * FROM teacher_student WHERE studentId = ? AND state = 2", ts.getStudentId());
        if (BeanUtil.isNotEmpty(tsConfirm)) {
            ts.delete();
            return Ret.fail().set("error", EnumError.STUDENT_HAVA_PAIR.getObj());
        }
        
        
        
        //添加绑定记录
        TsLog tsLog = new TsLog();
        tsLog.setAddTime(LocalDateTime.now());
        tsLog.setState(state);
        tsLog.setStudentId(ts.getStudentId());
        tsLog.setTeacherId(admin.getId());
        
        
          
                ts.setState(state);
                ts.setUpdateTime(LocalDateTime.now());
                //添加记录表
                TeacherStudentLog studentLog = TeacherStudentLog.dao.findFirst("SELECT * FROM teacher_student_log WHERE teacherId = ? AND studentId = ? AND state = 1 AND type = 1 ORDER BY id DESC", teacherId, ts.getStudentId());
                //查询绑定记录
                if (BeanUtil.isNotEmpty(studentLog)) {
                    studentLog.setState(state);
                    studentLog.setUpdateTime(LocalDateTime.now());
                    studentLog.setExamineId(admin.getId());
                    studentLog.update();
                    tsLog.setType(studentLog.getType());
                    tsLog.setTeacherStudentLogId(studentLog.getId());
                }
                
                ts.update();
                if (tsLog.getTeacherStudentLogId()!= null){
                    tsLog.save();
                }
            
        

        //给学生发送审核通知
        noticeDTO.setName(admin.getName());
        noticeDTO.setPic(admin.getAvatarUrl());
        noticeDTO.setAccountId(admin.getAccountId());
        noticeDTO.setType(9);
        noticeDTO.setPairState(state);
        noticeDTO.setPairType(1);
        ArrayList<Integer> list = new ArrayList<>();
        Student o = Redis.use().get(Const.user.Student + ts.getStudentId());
        list.add(o.getAccountId());
        ChatUtil.sendNotice(JSONUtil.toJsonStr(noticeDTO), 1, list);
        
        return Ret.ok();
    }


    /**
     * 获得教师绑定的学生的年级班级
     *
     * @param adminId
     * @return
     */
    public Ret findStuClassInfo(Integer adminId) {
        List<Record> records = Db.template("findStuClassInfo", Kv.by("adminId", adminId)).find();
        return Ret.ok("stuClassInfo", records);
    }

    public Ret cancelPairPage(Integer teacherId, Integer state, Integer page, Integer limit, String keyWord) {

        List<Record> recordList = Db.template("findCancelPair", Kv.by("teacherId", teacherId).setIfNotNull("state", state).setIfNotNull("keyWord", keyWord)).find();
        return Ret.ok("cancelPairList", recordList);
    }

    public Ret pairCancelConfirm(Admin admin, Integer pairId, Integer state) {
        Cache redis = Redis.use();
        AtomicInteger studentId = new AtomicInteger();
        Ret ret = Ret.create();
        Db.tx(Connection.TRANSACTION_REPEATABLE_READ, () -> {
            TeacherStudentLog first = TeacherStudentLog.dao.findFirst("SELECT * FROM teacher_student_log WHERE id = ? AND teacherId = ? AND type = 2 AND state = 1", pairId, admin.getId());
            if (BeanUtil.isEmpty(first)) {
                ret.setFail().set("error", EnumError.NOT_EXIT_CANCEL_PARI.getObj());
                return false;
            }

            studentId.set(first.getStudentId());
            if (state == 2) {
                Db.delete("DELETE FROM teacher_student WHERE teacherId = ? AND studentId = ? ", first.getTeacherId(), first.getStudentId());
            }
            TsLog tsLog = new TsLog();
            tsLog.setAddTime(LocalDateTime.now());
            tsLog.setState(state);
            tsLog.setStudentId(first.getStudentId());
            tsLog.setTeacherId(admin.getId());
            tsLog.setType(first.getType());
            tsLog.setTeacherStudentLogId(first.getId());

            first.setState(state);
            first.setExamineId(admin.getId());
            first.setUpdateTime(LocalDateTime.now());
            tsLog.save();
            first.update();
            ret.setOk();
            return true;
        });
        if (ret.isFail()) {
            return ret;
        }
        Integer stuId = studentId.get();
        ArrayList<Integer> list = new ArrayList<>();
        if (state == 2) {
            Student o = redis.get(Const.user.Student + stuId);
            o.put("teacher", null);
            o.put("teacherId", null);
            redis.set(Const.user.Student + stuId, o);
            //解除好友关系
            list.add(o.getAccountId());
            //发送解除好友关系通知
            Admin o1 = redis.get(Const.user.Admin + admin.getId());
            ChatUtil.deleFriends(o1.getAccountId(), list);
        }
        PairNoticeDTO noticeDTO = new PairNoticeDTO();
        noticeDTO.setName(admin.getName());
        noticeDTO.setPic(admin.getAvatarUrl());
        noticeDTO.setAccountId(admin.getAccountId());
        noticeDTO.setType(9);
        noticeDTO.setPairState(state);
        noticeDTO.setPairType(2);
        list.clear();
        Student o = redis.get(Const.user.Student + stuId);
        list.add(o.getAccountId());
        try {
            ChatUtil.sendNotice(JSONUtil.toJsonStr(noticeDTO), 1, list);
        } catch (Exception e) {

        }
        return Ret.ok();
    }


}
